<template>
  <span class=""> {{ formatTime(state.restTime) }} </span>
</template>
<script setup>
import { reactive, toRefs, ref, watch } from "vue";
const state = reactive({
  restTime: 0,
});

const emits = defineEmits(["end"]);

let timer;
const onWork = () => {
  timer && clearInterval(timer);
  timer = setInterval(() => {
    state.restTime--;
    if (state.restTime <= 0) {
      clearInterval(timer);
      emits("end");
    }
  }, 1000);
};

const formatUnit = inValue => {
  inValue = inValue + "";
  return inValue.padStart(2, "0");
};

const formatTime = totalSeconds => {
  // 计算分钟数
  const minutes = Math.floor(totalSeconds / 60);
  // 计算剩余的秒数
  const seconds = totalSeconds % 60;

  // 返回格式化后的分秒字符串
  return `${formatUnit(minutes)}分${formatUnit(seconds)}秒`;
};

defineExpose({
  reset(restTime = 180) {
    state.restTime = restTime;
    onWork();
  },
});
</script>
<style lang="scss"></style>
